package com.dimples.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dimples.common.constant.StrPool;
import com.dimples.common.properties.DimplesProperties;
import com.dimples.common.util.CommonUtil;
import com.dimples.common.util.HttpContextUtil;
import com.dimples.system.entity.SysFile;
import com.dimples.system.mapper.SysFileMapper;
import com.dimples.system.service.SysFileService;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.util.Date;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author zhongyj <1126834403@qq.com><br/>
 * @date 2021/6/27
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SysFileServiceImpl extends ServiceImpl<SysFileMapper, SysFile> implements SysFileService {

    private final DimplesProperties properties;
    private final SysFileMapper fileMapper;

    @Override
    public void download(String id) {
        try {
            LambdaQueryWrapper<SysFile> lambdaQuery = Wrappers.lambdaQuery(SysFile.class);
            lambdaQuery.eq(SysFile::getFileId, id).or().eq(SysFile::getFileName, id);
            SysFile file = this.fileMapper.selectOne(lambdaQuery);
            if (null == file) {
                file = new SysFile();
            }
            File files = FileUtil.file(file.getFilePath());
            if (FileUtil.exist(files)) {
                FileCopyUtils.copy(new FileInputStream(file.getFilePath()), HttpContextUtil.getResponse().getOutputStream());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String upload(MultipartFile file) {
        String result = "";
        try {
            String name = file.getOriginalFilename();
            assert name != null;
            String suffixName = FileUtil.getSuffix(name);
            String fileName = DateUtil.format(new Date(), DatePattern.PURE_DATETIME_MS_PATTERN) + StrPool.DOT + suffixName;
            String parentPath = properties.getFile().getUploadPath() + DateUtil.today();
            File filepath = FileUtil.file(parentPath, fileName);
            FileUtil.mkdir(filepath.getParentFile());

            String absolutePath = FileUtil.getAbsolutePath(filepath);
            file.transferTo(FileUtil.file(absolutePath));

            SysFile sysFile = new SysFile();
            sysFile.setFileDesc(name);
            sysFile.setFileName(fileName);
            sysFile.setTargetTime(DateUtil.parseDateTime(DateUtil.now()));
            sysFile.setFilePath(absolutePath);
            sysFile.setCreateTime(DateUtil.parseDateTime(DateUtil.now()));
            sysFile.setFileSize(CommonUtil.getPrintSize(filepath.length()));
            sysFile.setFileType(suffixName);
            int flag = this.fileMapper.insert(sysFile);
            if (flag > 0) {
                result = String.valueOf(sysFile.getFileId());
            } else {
                result = "";
            }
        } catch (Exception e) {
            log.error("failed to upload file.detail message:{}", e.getMessage());
        }
        return result;
    }
}

